<template>
  <div id="user">
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索与添加区域 -->
          <el-input placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable>
            <template #append>
              <el-button @click="handleSearch">
                <el-icon>
                  <search />
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
            @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域  -->
      <el-table :data="userlist"
        border
        stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="学号"
          prop="account"></el-table-column>
        <el-table-column label="密码"
          prop="pwd"
          width="190px"></el-table-column>
        <el-table-column label="token"
          prop="token"></el-table-column>
        <el-table-column label="角色"
          :formatter="formatRole"></el-table-column>
        <el-table-column label="操作"
          width="200px">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button type="primary"
              @click="showEditDialog(scope.row.account)">
              <el-icon>
                <edit />
              </el-icon>
            </el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false">
              <el-button type="warning">
                <el-icon>
                  <setting />
                </el-icon>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页面区域  分页跳转-->
      <el-pagination v-model:current-page="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog v-model="addDialogVisible"
      title="添加用户"
      width="50%"
      @close="addDialogClosed">
      <!-- 内容主体内容 -->
      <el-form :model="addForm"
        :rules="addFromRules"
        ref="addFormRef"
        label-width="70px">
        <el-form-item label="学号"
          prop="account">
          <el-input v-model="addForm.account"></el-input>
        </el-form-item>
        <el-form-item label="密码"
          prop="pwd">
          <el-input v-model="addForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="角色"
          prop="roleId">
          <el-select v-model="addForm.roleId"
            placeholder="请选择角色">
            <el-option label="教师"
              value="2"></el-option>
            <el-option label="学生"
              value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary"
            @click="submitAddForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog v-model="editDialogVisibel"
      title="修改用户"
      width="50%">
      <!-- 内容 -->
      <el-form :model="editFrom"
        ref="editFormRef"
        label-width="120px">
        <el-form-item label="学号">
          <el-input v-model="editFrom.account"
            disabled />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editFrom.pwd" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editFrom.roleId"
            placeholder="请选择角色">
            <el-option label="教师"
              value="2"></el-option>
            <el-option label="学生"
              value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisibel = false">取消</el-button>
          <el-button type="primary"
            @click="submitEditForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, addUser, updateUser, getUserById } from '@/api/user';

export default {
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "", // 查询参数
        pagenum: 1, // 当前页数
        pagesize: 5, // 每页显示条数
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        account: "",
        pwd: "",
        roleId: "3" // 默认选中学生
      },
      editDialogVisibel: false,
      addFromRules: {
        account: [{ required: true, message: "请输入学号", trigger: "blur" }],
        pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }]
      },
      editFrom: {
        uId: 0,
        account: "",
        pwd: "",
        roleId: 2
      },
      token: this.getCookie('authToken') || '',
      roleMap: {
        1: '管理员',
        2: '教师',
        3: '学生'
      }
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getCookie(name) {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      return parts.length === 2 ? parts.pop().split(';').shift() : '';
    },
    // 格式化角色显示
    formatRole(row) {
      return this.roleMap[row.roleId] || '未知角色';
    },
    // 使用封装的API获取用户列表
    async getUserList() {
      try {
        const userData = {
          query: this.queryInfo.query,
          token: this.token
        };
        const response = await getUserList(
          this.queryInfo.pagenum,
          this.queryInfo.pagesize,
          0,
          userData
        );
        
        if (response.code === 200) {
          this.total = response.data.total;
          this.userlist = response.data.list;
        } else {
          this.$message.error(response.msg || '获取用户列表失败');
        }
      } catch (error) {
        console.error('获取用户列表失败', error);
        this.$message.error('获取用户列表失败，请重试');
      }
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    addDialogClosed() {
      this.$refs.addFormRef?.resetFields();
      this.addForm.roleId = "3";
    },
    // 使用封装的API获取用户详情
    async showEditDialog(account) {
      this.editDialogVisibel = true;
      try {
        const response = await getUserById(account);
        if (response.code === 200) {
          const { uId, account, pwd, roleId } = response.data;
          this.editFrom = { uId, account, pwd, roleId };
        } else {
          throw new Error(response.msg || '获取用户数据失败');
        }
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    // 使用封装的API更新用户
    async submitEditForm() {
      try {
        await this.$refs.editFormRef.validate();
        const formData = {
          ...this.editFrom,
          token: this.token
        };
        
        const response = await updateUser(formData);
        if (response.code === 200) {
          this.$message.success('更新成功');
          this.editDialogVisibel = false;
          this.getUserList();
        } else {
          throw new Error(response.msg || '更新失败');
        }
      } catch (error) {
        this.$message.error(error.message || '更新失败，请重试');
      }
    },
    // 使用封装的API添加用户
    async submitAddForm() {
      try {
        await this.$refs.addFormRef.validate();
        const formData = {
          ...this.addForm,
          token: this.token
        };

        const loading = this.$loading({
          lock: true,
          text: '正在创建用户...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.1)'
        });

        const response = await addUser(formData);
        if (response.code === 200) {
          this.$message.success('用户添加成功');
          this.addDialogVisible = false;
          this.getUserList();
        } else {
          throw new Error(response.msg || '添加用户失败');
        }
      } catch (error) {
        this.$message.error(error.message || '添加用户失败，请重试');
      } finally {
        this.$loading().close();
      }
    }
  }
};
</script>